package com.yuan.dao.goods.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.SqlMapClientTemplate;

import com.yuan.dao.goods.GoodsDao;
import com.yuan.goods.Goods;
import com.yuan.merchant.Merchant;

public class GoodsDaoImpl extends SqlMapClientTemplate implements GoodsDao {

	private static final Logger logger = Logger.getLogger(GoodsDaoImpl.class);

	public void save(List<Goods> goodses) throws SQLException {
		try {
			this.getSqlMapClient().startBatch();

			for (Goods goods : goodses) {
				this.insert("Goods.save", goods);
			}

			this.getSqlMapClient().endTransaction();
		} catch (Exception e) {
			logger.error("Goods入库失败", e);
			throw new SQLException();
		}

	}

	public List<Goods> readToday(String tags) throws DataAccessException {

		Map<String, Object> args = new HashMap<String, Object>();
		args.put("today", new Date());

		if(tags!=null){
			String tagsLike="";	
			String [] tagses=tags.split(",");
			
			for (String string : tagses) {
				tagsLike+="AND tags like '%"+string+"%'";
			}
			args.put("tags", tagsLike);
		}else{
			args.put("tags", "");
		}
		
		List<Goods> goodses = this.queryForList("Goods.readToday", args);

		for (Goods goods : goodses) {
			Map<String, Object> args1 = new HashMap<String, Object>();
			args1.put("id", goods.getMerchantId());

			Merchant merchant = (Merchant) this.queryForObject(
					"Merchant.readById", args1);

			goods.setMerchant(merchant);
		}
		return goodses;
	}

}
